﻿using UnityEngine;
using System.Collections;

public class FallerControl : MonoBehaviour {

	public float maxSpeed = 3f;
	public float moveForce = 100f;

	private Rigidbody2D _rigidbody = null;
	private Animator _anim = null;

	private bool _isMoving = false;
	private bool _isFacingRight = false;

	void Awake() {
		this._anim = GetComponent<Animator>();
		this._rigidbody = this.rigidbody2D;
	}

	void OnCollisionEnter2D(Collision2D c) {
		if (GameManager.Instance.gameState == GameState.Over) return;
		if (c.gameObject.tag == "Enemy") {
			//每踩到一次平台就加分
			GameManager.Instance.AddScore();
		}
	}

	void FixedUpdate() {
		float h = Input.GetAxis("Horizontal");
		this._isMoving = !Mathf.Approximately(0f, h);
		this._anim.SetBool("IsMoving", this._isMoving);

		if (this._isMoving) {
			//控制左右移動
			if (h * this._rigidbody.velocity.x < maxSpeed)
				this._rigidbody.AddForce(Vector2.right * h * moveForce);

			if (Mathf.Abs(this._rigidbody.velocity.x) > maxSpeed)
				this._rigidbody.velocity = new Vector2(Mathf.Sign(this._rigidbody.velocity.x) * maxSpeed, this._rigidbody.velocity.y);
		}

		//切換圖顯示的方向
		if (h > 0 && !this._isFacingRight)
			Flip();
		else if (h < 0 && this._isFacingRight)
			Flip();
	}

	private void Flip() {
		this._isFacingRight = !this._isFacingRight;
		this.transform.localRotation = Quaternion.Euler(0f, this._isFacingRight ? 180f : 0f, 0f);
	}
}
